package com.spark.modules.system.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spark.modules.system.entity.SysPermission;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成路由
 *
 * @author LYCHEE
 * @date 2025/3/26 14:33
 */
public class RouteConverter {

    public List<Map<String, Object>> convertToRouteTree(List<SysPermission> permissions) {
        // 1. 转换为带有meta的扁平路由列表
        List<Map<String, Object>> routes = permissions.stream()
                .filter(p -> p.getType() != 2)
                .map(this::convertToRoute)
                .collect(Collectors.toList());

        // 2. 构建树形结构
        Map<String, Map<String, Object>> nodeMap = new LinkedHashMap<>();
        List<Map<String, Object>> rootNodes = new ArrayList<>();

        // 创建所有节点映射
        routes.forEach(route -> {
            String id = (String) route.get("id");
            nodeMap.put(id, route);
        });

        // 构建父子关系
        routes.forEach(route -> {
            String pid = (String) route.get("pid");
            if ("0".equals(pid)) {
                rootNodes.add(route);
            } else {
                Map<String, Object> parent = nodeMap.get(pid);
                if (parent != null) {
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parent.getOrDefault("children", new ArrayList<>());
                    children.add(route);
                    parent.put("children", children);
                }
            }
        });

        // 3. 排序处理
        sortRoutes(rootNodes);
        return rootNodes;
    }

    private Map<String, Object> convertToRoute(SysPermission permission) {
        Map<String, Object> route = new LinkedHashMap<>();
        Map<String, Object> meta = new LinkedHashMap<>();

        // 必须保留原始ID和PID
        route.put("id", permission.getId());
        route.put("pid", permission.getPid());

        // 基础路由属性
        route.put("path", permission.getRoutePath());
        route.put("name", permission.getRoutePath());
        route.put("component", permission.getComponentPath());

        // Meta字段映射
        meta.put("title", permission.getName());
        meta.put("icon", permission.getIcon());
        meta.put("order", permission.getSortRank() == null ? 0 : permission.getSortRank());
        meta.put("query", parseQuery(permission.getQuery()));

        // 布尔类型字段处理
        if (convertBool(permission.getIsAffixTab())) {
            meta.put("affixTab", true);
        }
        if (convertBool(permission.getIsKeepAlive())){
            meta.put("keepAlive", true);
        }

        if (convertBool(permission.getIsHideInMenu())){
            meta.put("hideInMenu", true);
        }

        if (convertBool(permission.getIsHideInTab())){
            meta.put("hideInTab", true);
        }

        if (convertBool(permission.getIsHideInBreadcrumb())){
            meta.put("hideInBreadcrumb", true);
        }

        if (convertBool(permission.getIsHideChildrenInMenu())){
            meta.put("hideChildrenInMenu", true);
        }

        if (convertBool(permission.getOpenInNewWindow())){
            meta.put("openInNewWindow", true);
        }

        if (convertBool(permission.getIsMenuVisibleWithForbidden())){
            meta.put("menuVisibleWithForbidden", true);
        }

        // 徽标处理
        if (convertBool(permission.getIsBadge())) {
            meta.put("badgeType", permission.getBadgeType());
            // 类型 红点 | 文本
            if ("dot".equals(permission.getBadgeType())){
                meta.put("badgeVariants",permission.getBadgeVariants());
            }else {
                meta.put("badge",permission.getBadgeValue());
                meta.put("badgeVariants",permission.getBadgeVariants());
            }
        }

        // 外链处理
        if (convertBool(permission.getIsLink()) && StringUtils.isNotEmpty(permission.getLink())) {
            if (0 == permission.getLinkOpenWay()){
                meta.put("link",permission.getLink());
            }else {
                meta.put("iframeSrc",permission.getLink());
            }
        }

        // 权限处理
        if (StringUtils.isNotBlank(permission.getAuthorityStr())) {
            meta.put("authority", Arrays.asList(permission.getAuthorityStr().split(",")));
        }

        route.put("meta", meta);
        return route;
    }


    // 类型转换工具方法
    private boolean convertBool(Integer value) {
        return value != null && value == 0;
    }

    private boolean convertBoolReverse(Integer value) {
        return value != null && value == 1;
    }

    private Map<String, Object> parseQuery(String query) {
        try {
            return StringUtils.isBlank(query) ?
                    Collections.emptyMap() :
                    new ObjectMapper().readValue(query, Map.class);
        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }

    // 递归排序方法
    private void sortRoutes(List<Map<String, Object>> routes) {
        routes.sort(Comparator.comparingInt(
                r -> (Integer) ((Map) r.get("meta")).getOrDefault("order", 0))
        );
        routes.forEach(route -> {
            if (route.containsKey("children")) {
                sortRoutes((List<Map<String, Object>>) route.get("children"));
            }
        });
    }
}
